<template>
  <v-dialog 
    :model-value="modelValue" 
    @update:model-value="$emit('update:modelValue', $event)"
    max-width="600px"
    persistent
  >
    <v-card>
      <v-card-title class="d-flex align-center justify-space-between">
        <span>{{ isEditing ? '编辑任务' : '新建任务' }}</span>
        <v-btn
          icon="mdi-close"
          variant="text"
          size="small"
          @click="closeDialog"
        />
      </v-card-title>
      
      <v-card-text>
        <v-form ref="formRef" v-model="formValid">
          <!-- 任务标题 -->
          <v-text-field
            v-model="formData.title"
            label="任务标题"
            :rules="titleRules"
            variant="outlined"
            density="comfortable"
            autofocus
            class="mb-4"
          />
          
          <!-- 任务描述 -->
          <v-textarea
            v-model="formData.description"
            label="任务描述（可选）"
            variant="outlined"
            density="comfortable"
            rows="3"
            auto-grow
            class="mb-4"
          />
          
          <!-- 截止日期和时间 -->
          <div class="d-flex gap-4 mb-4">
            <v-text-field
              v-model="dueDateFormatted"
              label="截止日期"
              variant="outlined"
              density="comfortable"
              readonly
              @click="showDatePicker = true"
              append-inner-icon="mdi-calendar"
              class="flex-grow-1"
            />
            
            <v-text-field
              v-model="dueTimeFormatted"
              label="截止时间"
              variant="outlined"
              density="comfortable"
              readonly
              @click="showTimePicker = true"
              append-inner-icon="mdi-clock"
              :disabled="!formData.dueDate"
              class="flex-grow-1"
            />
          </div>
          
          <!-- 提醒设置 -->
          <v-text-field
            v-model="reminderFormatted"
            label="提醒时间（可选）"
            variant="outlined"
            density="comfortable"
            readonly
            @click="showReminderPicker = true"
            append-inner-icon="mdi-bell"
            class="mb-4"
          />
          
          <!-- 优先级和重要性 -->
          <div class="d-flex gap-4 mb-4">
            <v-select
              v-model="formData.priority"
              label="优先级"
              :items="priorityOptions"
              variant="outlined"
              density="comfortable"
              class="flex-grow-1"
            />
            
            <v-switch
              v-model="formData.isImportant"
              label="重要任务"
              color="error"
              density="comfortable"
              hide-details
            />
          </div>
          
          <!-- 重复设置 -->
          <v-select
            v-model="formData.repeat.type"
            label="重复设置"
            :items="repeatOptions"
            variant="outlined"
            density="comfortable"
            class="mb-4"
            @update:model-value="onRepeatTypeChange"
          />
          
          <!-- 自定义重复天数 -->
          <v-text-field
            v-if="formData.repeat.type === 'custom'"
            v-model.number="formData.repeat.customDays"
            label="重复间隔（天）"
            type="number"
            variant="outlined"
            density="comfortable"
            min="1"
            class="mb-4"
          />
          
          <!-- 标签 -->
          <v-combobox
            v-model="formData.tags"
            label="标签（可选）"
            variant="outlined"
            density="comfortable"
            multiple
            chips
            closable-chips
            :items="availableTags"
            class="mb-4"
          />
          
          <!-- 所属清单 -->
          <v-select
            v-model="formData.listId"
            label="所属清单"
            :items="listOptions"
            variant="outlined"
            density="comfortable"
            class="mb-4"
          />
        </v-form>
      </v-card-text>
      
      <v-card-actions class="px-6 pb-4">
        <v-spacer />
        <v-btn
          variant="text"
          @click="closeDialog"
        >
          取消
        </v-btn>
        <v-btn
          color="primary"
          variant="flat"
          :disabled="!formValid"
          @click="saveTask"
        >
          {{ isEditing ? '保存' : '创建' }}
        </v-btn>
      </v-card-actions>
    </v-card>
    
    <!-- 日期选择器 -->
    <v-dialog v-model="showDatePicker" max-width="400px">
      <v-card>
        <v-card-title>选择截止日期</v-card-title>
        <v-card-text>
          <v-date-picker
            v-model="selectedDate"
            :min="new Date().toISOString().split('T')[0]"
            @update:model-value="onDateSelected"
          />
        </v-card-text>
        <v-card-actions>
          <v-btn variant="text" @click="clearDate">清除</v-btn>
          <v-spacer />
          <v-btn variant="text" @click="showDatePicker = false">取消</v-btn>
          <v-btn color="primary" @click="confirmDate">确定</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
    
    <!-- 时间选择器 -->
    <v-dialog v-model="showTimePicker" max-width="400px">
      <v-card>
        <v-card-title>选择截止时间</v-card-title>
        <v-card-text>
          <v-time-picker
            v-model="selectedTime"
            format="24hr"
            @update:model-value="onTimeSelected"
          />
        </v-card-text>
        <v-card-actions>
          <v-btn variant="text" @click="clearTime">清除</v-btn>
          <v-spacer />
          <v-btn variant="text" @click="showTimePicker = false">取消</v-btn>
          <v-btn color="primary" @click="confirmTime">确定</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
    
    <!-- 提醒时间选择器 -->
    <v-dialog v-model="showReminderPicker" max-width="400px">
      <v-card>
        <v-card-title>设置提醒时间</v-card-title>
        <v-card-text>
          <v-date-picker
            v-model="reminderDate"
            :min="new Date().toISOString().split('T')[0]"
            class="mb-4"
          />
          <v-time-picker
            v-model="reminderTime"
            format="24hr"
          />
        </v-card-text>
        <v-card-actions>
          <v-btn variant="text" @click="clearReminder">清除</v-btn>
          <v-spacer />
          <v-btn variant="text" @click="showReminderPicker = false">取消</v-btn>
          <v-btn color="primary" @click="confirmReminder">确定</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </v-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch, nextTick } from 'vue'
import type { Task } from '@/stores/taskStore'
import { useListStore } from '@/stores/listStore'

interface Props {
  modelValue: boolean
  task?: Task | null
  defaultListId?: string
}

interface Emits {
  'update:modelValue': [value: boolean]
  'save': [task: Partial<Task>]
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const listStore = useListStore()

// 表单引用和验证
const formRef = ref()
const formValid = ref(false)

// 对话框状态
const showDatePicker = ref(false)
const showTimePicker = ref(false)
const showReminderPicker = ref(false)

// 日期时间选择器状态
const selectedDate = ref<string | null>(null)
const selectedTime = ref<string | null>(null)
const reminderDate = ref<string | null>(null)
const reminderTime = ref<string | null>(null)

// 表单数据
const formData = ref<Partial<Task>>({
  title: '',
  description: '',
  dueDate: null,
  reminder: null,
  priority: 'low',
  isImportant: false,
  repeat: null,
  tags: [],
  listId: props.defaultListId || 'today',
  completed: false
})

// 计算属性
const isEditing = computed(() => !!props.task)

const dueDateFormatted = computed(() => {
  if (!formData.value.dueDate) return ''
  return new Date(formData.value.dueDate).toLocaleDateString('zh-CN')
})

const dueTimeFormatted = computed(() => {
  if (!formData.value.dueDate) return ''
  return new Date(formData.value.dueDate).toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
  })
})

const reminderFormatted = computed(() => {
  if (!formData.value.reminder) return ''
  return new Date(formData.value.reminder).toLocaleString('zh-CN')
})

const listOptions = computed(() => {
  return listStore.lists
    .filter(list => !list.isSystem)
    .map(list => ({
      title: list.name,
      value: list.id
    }))
})

// 表单验证规则
const titleRules = [
  (v: string) => !!v || '任务标题不能为空',
  (v: string) => v.length <= 100 || '任务标题不能超过100个字符'
]

// 选项数据
const priorityOptions = [
  { title: '低优先级', value: 'low' },
  { title: '中优先级', value: 'medium' },
  { title: '高优先级', value: 'high' }
]

const repeatOptions = [
  { title: '不重复', value: null },
  { title: '每天', value: 'daily' },
  { title: '每周', value: 'weekly' },
  { title: '每月', value: 'monthly' },
  { title: '自定义', value: 'custom' }
]

const availableTags = ref(['工作', '学习', '生活', '购物', '健康', '娱乐'])

// 监听器
watch(() => props.modelValue, (newValue) => {
  if (newValue) {
    resetForm()
    if (props.task) {
      loadTaskData()
    }
  }
})

watch(() => props.task, () => {
  if (props.modelValue && props.task) {
    loadTaskData()
  }
})

// 方法
const resetForm = () => {
  formData.value = {
    title: '',
    description: '',
    dueDate: null,
    reminder: null,
    priority: 'low',
    isImportant: false,
    repeat: null,
    tags: [],
    listId: props.defaultListId || 'today',
    completed: false
  }
  selectedDate.value = null
  selectedTime.value = null
  reminderDate.value = null
  reminderTime.value = null
  
  nextTick(() => {
    formRef.value?.resetValidation()
  })
}

const loadTaskData = () => {
  if (!props.task) return
  
  formData.value = { ...props.task }
  
  // 设置日期时间选择器的值
  if (props.task.dueDate) {
    const dueDate = new Date(props.task.dueDate)
    selectedDate.value = dueDate.toISOString().split('T')[0]
    selectedTime.value = dueDate.toTimeString().slice(0, 5)
  }
  
  if (props.task.reminder) {
    const reminder = new Date(props.task.reminder)
    reminderDate.value = reminder.toISOString().split('T')[0]
    reminderTime.value = reminder.toTimeString().slice(0, 5)
  }
}

const closeDialog = () => {
  emit('update:modelValue', false)
}

const saveTask = async () => {
  const { valid } = await formRef.value.validate()
  if (!valid) return
  
  const taskData = { ...formData.value }
  
  // 处理空值
  if (!taskData.description?.trim()) {
    taskData.description = undefined
  }
  if (!taskData.tags?.length) {
    taskData.tags = undefined
  }
  if (!taskData.repeat?.type) {
    taskData.repeat = undefined
  }
  
  emit('save', taskData)
  closeDialog()
}

// 日期时间处理方法
const onDateSelected = (date: string) => {
  selectedDate.value = date
}

const confirmDate = () => {
  if (selectedDate.value) {
    const date = new Date(selectedDate.value)
    if (selectedTime.value) {
      const [hours, minutes] = selectedTime.value.split(':')
      date.setHours(parseInt(hours), parseInt(minutes))
    } else {
      date.setHours(23, 59) // 默认设置为当天结束
    }
    formData.value.dueDate = date
  }
  showDatePicker.value = false
}

const clearDate = () => {
  selectedDate.value = null
  selectedTime.value = null
  formData.value.dueDate = null
  showDatePicker.value = false
}

const onTimeSelected = (time: string) => {
  selectedTime.value = time
}

const confirmTime = () => {
  if (selectedDate.value && selectedTime.value) {
    const date = new Date(selectedDate.value)
    const [hours, minutes] = selectedTime.value.split(':')
    date.setHours(parseInt(hours), parseInt(minutes))
    formData.value.dueDate = date
  }
  showTimePicker.value = false
}

const clearTime = () => {
  selectedTime.value = null
  if (selectedDate.value) {
    const date = new Date(selectedDate.value)
    date.setHours(23, 59)
    formData.value.dueDate = date
  }
  showTimePicker.value = false
}

const confirmReminder = () => {
  if (reminderDate.value && reminderTime.value) {
    const date = new Date(reminderDate.value)
    const [hours, minutes] = reminderTime.value.split(':')
    date.setHours(parseInt(hours), parseInt(minutes))
    formData.value.reminder = date
  }
  showReminderPicker.value = false
}

const clearReminder = () => {
  reminderDate.value = null
  reminderTime.value = null
  formData.value.reminder = null
  showReminderPicker.value = false
}

const onRepeatTypeChange = (type: string | null) => {
  if (type) {
    formData.value.repeat = {
      type,
      customDays: type === 'custom' ? 1 : undefined
    }
  } else {
    formData.value.repeat = null
  }
}
</script>

<style scoped>
.v-card-title {
  padding: 16px 24px;
  border-bottom: 1px solid rgb(var(--v-theme-surface-variant));
}

.v-card-text {
  padding: 24px;
}

.v-card-actions {
  padding: 16px 24px;
  border-top: 1px solid rgb(var(--v-theme-surface-variant));
}
</style>